package com.chenfan.magic.entity;

import lombok.Data;

import java.io.Serializable;

/**
 * 资源计算模型
 *
 * @author 周夕
 * @date 2020-03-05 13:02
 */
@Data
public class MemoryModel implements Serializable {

    private static final long serialVersionUID = 1L;

    private Runtime runtime = Runtime.getRuntime();

    private MemoryDetailModel startMem = new MemoryDetailModel();

    private MemoryDetailModel endMem = new MemoryDetailModel();

    private long useMem;


    public MemoryModel start(boolean gc) {
//        System.in.read();//暂停程序执行, 增强计算精度.

//        if (gc) {
//            this.runtime.gc();//手动 GC, 清空之前的内存占用.
//        }
        this.startMem.setTotalMemory(this.runtime.totalMemory());
        this.startMem.setFreeMemory(this.runtime.freeMemory());
        this.startMem.setUsedMemory(this.runtime.totalMemory() - this.runtime.freeMemory());
        return this;
    }

    public MemoryModel start() {
        return this.start(false);
    }

    public MemoryModel end(boolean gc) {
        this.endMem.setTotalMemory(this.runtime.totalMemory());
        this.endMem.setFreeMemory(this.runtime.freeMemory());
        this.endMem.setUsedMemory(this.runtime.totalMemory() - this.runtime.freeMemory());
        this.useMem = this.endMem.getUsedMemory() - this.startMem.getUsedMemory();
//        if (gc) {
//            this.runtime.gc();//手动 GC, 清空内存占用.
//        }
        return this;
    }

    public MemoryModel end() {
        return this.end(false);
    }
}
